package main.alarms;

import java.util.ArrayList;

import com.google.gson.Gson;

import main.activities.NewAlarmActivity;
import main.adapter.AlarmsListAdapter;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
	private TextView btnAddNewAlarm;
	private AlarmsManager am;
	private ArrayList<AlarmInfo> alarmsAll;
	private AlarmsListAdapter adapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 获取闹钟管理器
		this.am = new AlarmsManager(this);
		// 获取保存的所有闹钟
		this.alarmsAll = am.getAllAlarmInfo();

		// 将所有闹钟数据放置到列表中
		// ListView alarmsList = (ListView) this.findViewById(R.id.alarmsList);
		if (this.alarmsAll != null) {
			try {
				this.adapter=new AlarmsListAdapter(this, this.alarmsAll);
				this.setListAdapter(this.adapter);
			} catch (NullPointerException e) {
				e.printStackTrace();
			}

		}

		// 添加现有闹钟点击事件
		// TODO 添加现有闹钟点击事件
		// alarmsList.setOnItemClickListener(listener);
		// alarmsList.setOnItemSelectedListener(listener);

		// 添加新闹钟事件处理
		btnAddNewAlarm = (TextView) this.findViewById(R.id.btnAddNewAlarm);
		btnAddNewAlarm.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// Toast.makeText(MainActivity.this, "sss", Toast.LENGTH_LONG);
				try {
					Intent i = new Intent(MainActivity.this,
							NewAlarmActivity.class);
					Bundle bundleRet = new Bundle();
					bundleRet.putInt("state", 1);// 1 new alarm 2 edit alarm;
					i.putExtra("data", bundleRet);
					// bundleRet.put
					MainActivity.this.startActivityForResult(i, 1);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

	}

	// NewAlarmAcitity 窗口点击确认时回调函数
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode != RESULT_CANCELED) {
			if (requestCode == 1) {
				AlarmInfo info = new AlarmInfo();
				Bundle bundleRet = data.getExtras();
				String info_json = bundleRet.getString("info_json");
				Gson gson = new Gson();
				info = gson.fromJson(info_json, AlarmInfo.class);
				// 添加一个闹钟
				this.am.addNewAlarm(info);
//				this.alarmsAll.add(info);
				this.adapter=new AlarmsListAdapter(this, this.alarmsAll);
				this.setListAdapter(this.adapter);
				this.adapter.notifyDataSetChanged();
				
				// 更新listView
				// TODO 更新listView
			}
		}

	}
}